package com.bao.auth.server.controller.auth;

import com.bao.auth.dto.auth.LoginDTO;
import com.bao.auth.dto.auth.LoginParamDTO;
import com.bao.auth.server.biz.service.auth.ValidateCodeService;
import com.bao.auth.server.biz.service.auth.impl.AuthManager;
import com.bao.core.base.BaseController;
import com.bao.core.base.R;
import com.bao.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
@Api(value = "LoginController",tags = "登录")
@Slf4j
public class LoginController extends BaseController {

    @Qualifier("ValidateCodeServiceImpl")
    @Autowired
    private ValidateCodeService validateService;
    
    @Autowired
    private AuthManager authManager;
    
    @RequestMapping(value = "captcha", method = RequestMethod.GET, produces = "image/png")
    @ApiOperation(value = "验证码", notes = "验证码")
    @ApiImplicitParam(name = "key",value = "验证码key", required = true)
    @SysLog("生成验证码")
    public void captcha(String key, HttpServletResponse response) throws IOException {
        validateService.create(key,response);
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ApiOperation(value = "登录", notes = "登录")
    @SysLog("用户登录")
    public R<LoginDTO> login(@Validated @RequestBody LoginParamDTO loginParamDTO){
        //校验前端上传的验证码是否正确
        boolean check = validateService.check(loginParamDTO.getKey(), loginParamDTO.getCode());
        if (check){
            //验证码校验通过，执行具体登录认证逻辑
            R<LoginDTO> login = authManager.login(loginParamDTO.getAccount(), loginParamDTO.getPassword());
            return login;
        }
        return this.validFail("验证码有误，请重新输入");
    }

    //校验验证码
    @PostMapping("/check")
    @ApiOperation(notes = "校验验证码",value = "校验验证码")
    public boolean check(@RequestBody LoginParamDTO loginParamDTO){
        //校验验证码是否正确
        return validateService.check(loginParamDTO.getKey(),loginParamDTO.getCode());
    }
}
